{            
Indicator:     _FxDeviation

Description:    Plots the deviation of three prices (Price1, Price2 and Price3) from a user specified
                reference function, such as: AMA, EMA, Linear Regression curve, Tilson T3 average,
                Jurik moving average, or a constant value.

                Indicator can be smoothed or rounded to nearest tradable value.

Provided By:    MarkSanDiego

Updated:        09/09/08    original version
                01/23/11    StdDevLength and StdErrLength set to RefParam[1] (IDRef Length) if not otherwise specified
                12/11/11    calculation bug fixed
                01/01/12    minimum length for standard error is 3
                03/07/12    corrected Case 8 reference value formula to include offset.
                12/04/12    LinRegFaster function substituted for LinearReg
                12/11/12    _StdDevMean function substituted for _StdDev, since exporting to *.ELD files does not always included nested function calls
                12/14/12    calculating functions without offset provides greater flexibility in using indicator with both historical and real data  
                10/15/15    minor documentation and variable name changes 

}

Input:     
    Price1(close), 
    Price2(0), 
    Price3(0),
    RefPrice(avgprice), 
    Offset(6),

    RefID(3),                           { reference function identifier }
    AMALength(15),                      { arithmetic moving average length }
    EMALength(15),                      { exponential moving average length }
    LRLength(80),                       { linear regression function length }
    KAMA_EffRatioLen(7),                { Kaufman adaptive moving average parameters }
    KAMA_FastLength(2),                 { Kaufman adaptive moving average parameters }
    KAMA_SlowLength(25),                { Kaufman adaptive moving average parameters }
    T3Length(20),                       { Tilson T3 moving average length }
    JMALength(20),                      { Jurik moving average length }
    JMAPhase(0),                        { Jurik moving average phase parameter }
    __VWAP("No parameter - RefID = 7"),
    RefValue(0),                        { define zero deviation to be this fixed value }

    DevID(2),                           { deviation function identifier }
    StdDevLength(0),                    { standard deviation length.  If zero, assumes LRLength }
    StdErrLength(0),                    { standard error length.  If zero, assumes LRLength }
    ATRLength(14),                      { average true range length }
    JATRLength(14),                     { percentage }
    Percent(1),                         { points }     
    Pts(1),

    Ref1(0), 
    Ref2(0), 
    Ref3(0),
    Ref4(0),
    Ref5(0),
    Ref6(0);

Vars: 
    LRTgtBar(-Offset),                  { linear regression function target bar is always set equal to - Offset }
    Intrabarpersist DevLength(0),
    TgtBar(-Offset),                    { Linear regression Target Bar is always Equals to -Offset }
    intrabarpersist oRef(0), 
    Intrabarpersist oRef2(0),
    intrabarpersist oUnitDev(0),
    Intrabarpersist oUnitDev2(0),
    intrabarpersist oLRSlope(0),
    Intrabarpersist oLRAngle(0),  
    Intrabarpersist oLRIntercept(0),  
    intrabarpersist oDev1(0), 
    intrabarpersist oDev2(0), 
    intrabarpersist oDev3(0),
    intrabarpersist oMean(0), 
    intrabarpersist L1(0),
    intrabarpersist L2(0);

{ Methods begin /////////////////////////////////////////////////////////////////////////////////// }
{
Method  :       FxDeviation  

Description:    This method calculates the unit deviation from a defined reference.

                In general, this method should be called only during BarStatus(1) = 2 conditions
                as the result values only change once per bar

Provided By:    Mark J. Krisburg

Modified:       12/16/11    original version
                

RefID:          (0) RefPrice (input RefPrice without averaging )
                (1) Simple Moving Average 
                (2) Exponential Moving Average 
                (3) Linear Regression 
                (4) T3 Average
                (5) Jurik Moving Average
                (6) Reference Value 

DevID:          (0) Raw deviation without further processing 
                (1) Standard Deviations ( Param=SDLength )
                (2) Standard Error ( Parm = SELength )
                (3) AvgTrueRange ( Param=ATRLength )
                (4) JMA True Range ( ATR using Juric moving average )
                (5) Percent
                (6) Points

}
{ inputs defined in calling routine - exclude these when inserting Method in Main program }
{
Inputs:
    RefPrice(AvgPrice),
    xOffset(0),
    RefID(3),                       { reference function identifier }
    AMALength(15),                  { arithmetic moving average length }
    EMALength(15),                  { exponential moving average length }
    LRLength(120),                  { linear regression function length }
    LRTgtBar(-6),                   { linear regression function target bar }
    KAMA_EffRatioLen(7),            { Kaufman adaptive moving average parameters }
    KAMA_FastLength(2),             { Kaufman adaptive moving average parameters }
    KAMA_SlowLength(25),            { Kaufman adaptive moving average parameters }
    T3Length(20),                   { Tilson T3 moving average length }
    JMALength(20),                  { Jurik moving average length }
    JMAPhase(0),                    { Jurik moving average phase parameter }
    __VWAP("No parameter - RefID = 7"),
    RefValue(0),                    { define zero deviation to be this fixed value }

    DevID(2),                       { deviation function identifier }
    StdDevLength(0),                { standard deviation length }
    StdErrLength(0),                { standard error length }
    ATRLength(14),                  { average true range length }
    JATRLength(14),                 { percentage }
    Percent(1),                     { points }     
    Pts(1);
    
{ variables defined in calling routine - exclude these when inserting Method in Main program }
 Vars:  
    Intrabarpersist DevLength(0),
    
      { outputs } 
    oRef(0), 
    oUnitDev(0),
    oLRSlope(0),
    oLRAngle(0),
    oLRIntercept(0),
    oMean(0);
}
Method void FxDeviation()
begin      
    
    switch RefID begin  
        Case 0:
            oRef = RefPrice[Offset];
        Case 1:
            oRef = AverageFC(RefPrice[Offset], AMALength);
        Case 2:
            oRef = XAverage(RefPrice[Offset], EMALength);
        Case 3:
            value1 = _LinearRegFaster( RefPrice[Offset], LRLength, LRTgtBar, oLRSlope, oLRAngle, oLRIntercept, oRef) ;            
        Case 4:
            oRef = AdaptiveMovAvg(RefPrice[Offset],  KAMA_EffRatioLen, KAMA_FastLength, KAMA_SlowLength);
        Case 5:
            oRef = T3Average.series(RefPrice[Offset], T3Length);
        
        // uncomment the next two lines if you have purchased Jurik Moving Average functions
//        Case 6:    
//            oRef = JRC.JMA.2K(RefPrice[Offset], JMALength, JMAPhase);
        Case 7:
            oRef = _VWAP[Offset];
        Case 8:
            oRef = RefValue;
    end;

 
     Once Begin
         switch DevID begin
             Case 1:
                L1 = MaxList(2, iff(StdDevLength > 0, StdDevLength, LRLength));     { StdDev Length must be >= 2 }
            Case 2:
                L2 = MaxList(3, iff(StdErrLength > 0, StdErrLength, LRLength));     { StdErr Length must be >= 3 }
         end;    
     end;
 
 
    switch DevID begin
        Case 0:                    
            oUnitDev = 1;            { raw deviation without processing }
        Case 1:
            value1 = _StdDevMean(RefPrice[Offset], L1, 1, oMean, oUnitDev);
        Case 2:
            oUnitDev = StdError(RefPrice[Offset], L2);
        Case 3:
            oUnitDev2 = _AvgTrueRange(ATRLength);
            oUnitDev = oUnitDev2[Offset];
        
//       uncomment the next two lines if you have purchased Jurik Moving Average functions
//        case 4:
//            oUnitDev = _JMATrueRange(JATRLength);
        Case 5:
            oUnitDev = RefPrice[Offset] * Percent / 100; 
        Case 6:
            oUnitDev = Pts;
    end;

end;  

{ Methods end  ////////////////////////////////////////////////////////////////////////////////////// }  



#region Main Program   

    #region Tick Processing
            
        { prevent divide by zero }
        if oUnitDev <> 0 then begin             
            oDev1 = (Price1 - oRef)/oUnitDev;
            oDev2 = (Price2 - oRef)/oUnitDev;
            oDev3 = (Price3 - oRef)/oUnitDev;
        end;
     
        { indicator output }
        if Price1 <> 0 then plot1(oDev1,"Dev-1");
        if Price2 <> 0 then plot2(oDev2,"Dev-2");
        if Price3 <> 0 then plot3(oDev3,"Dev-3");
    
        If Ref1 <> 0 Then Plot4(Ref1,"Ref-1");
        If Ref2 <> 0 Then Plot5(Ref2,"Ref-2");
        If Ref3 <> 0 Then Plot6(Ref3,"Ref-3");
        If Ref4 <> 0 Then Plot7(Ref4,"Ref-4");
        If Ref5 <> 0 Then Plot8(Ref5,"Ref-5");
        If Ref6 <> 0 Then Plot9(Ref6,"Ref-6");
        
    #endregion     {Tick Processing }    
    
    
    #region EndOfBar Processing
    
        { Repeat calculation with each new bar }
            if BarStatus(1) = 2 then begin
                FxDeviation();
            end;
                
    #endregion


#endregion   { Main Program }